//
//  ByCoreDataBase.m
//  beibei_ios
//
//  Created by pro on 16/5/7.
//  Copyright © 2016年 hebidu. All rights reserved.
//

#import "ByCoreDataBase.h"

#import "FastCoder.h"
#import "FMDB.h"

#import "ByCoreProvinceModel.h"
#import "ByCoreCityModel.h"
#import "ByCoreAreaModel.h"


static FMDatabaseQueue *_dbQueue;

@implementation ByCoreDataBase

+ (void)logDBPath {
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filename = [doc stringByAppendingPathComponent:@"itboye_cache.db"];
    NSLog(@"数据库文件绝对路径****/n%@", filename);
}

/**
 *  创建数据库，并加入到队列中，此时已经默认打开了数据库，无须手动打开，只需要从队列中去取数据库即可
 */
+ (void)openDB {
    

    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filename = [doc stringByAppendingPathComponent:@"itboye_cache.db"];
//    NSLog(@"数据库文件绝对路径****\n%@", filename);
    // 把数据库文件从工程文件及中赋值到Documents中
    if (![[NSFileManager defaultManager] fileExistsAtPath:filename]) {

        NSString *databasePath = [[NSBundle mainBundle] pathForResource:@"itboye" ofType:@"db"];
        
        if ([[NSFileManager defaultManager] copyItemAtPath:databasePath toPath:filename error:nil]) {
            NSLog(@"数据库文件成功拷贝到沙盒中!");
        } else {
            NSLog(@"数据库文件拷贝到沙盒中失败!");
        };
    }
    
    // 创建数据库，并加入到队列中，此时已经默认打开了数据库，无须手动打开，只需要从队列中去取数据库即可
    if (!_dbQueue) {
        _dbQueue = [FMDatabaseQueue databaseQueueWithPath:filename];
    }
}


+ (NSArray *)query {
    
    [self openDB];
    
    NSMutableArray *ary = [[NSMutableArray alloc] init];
    
    [_dbQueue inDatabase:^(FMDatabase *db) {
        
        // 开启事务:事务对于数据库的作用是对数据的一系列操作，要么全部成功，要么全部失败，防止中间状态的出现，以确保数据库中的数据始终处于正确及和谐状态。
        [db beginTransaction];
        FMResultSet *set = [db executeQuery:@"SELECT * FROM common_cache"];
        
        // 遍历结果集
        while ([set next]) {
            ByCoreCacheModel *model = [[ByCoreCacheModel alloc] init];
            model._id = [set intForColumn:@"id"];
            model.key = [set stringForColumn:@"key"];
            model.value = [set dataForColumn:@"value"];
            model.type = [set stringForColumn:@"type"];
            model.update_time = [set intForColumn:@"update_time"];
            model.expire_time = [set intForColumn:@"expire_time"];
            [ary addObject:model];
        }
        [set close];
        [db commit];
    }];
    
    return ary;
}

+ (ByCoreCacheModel *)queryWithKey:(NSString *)key {
    
    [self openDB];
    
    ByCoreCacheModel *model = [[ByCoreCacheModel alloc] init];
    
    [_dbQueue inDatabase:^(FMDatabase *db) {
        
        [db beginTransaction];
        FMResultSet *set = [db executeQuery:@"SELECT * FROM common_cache WHERE key = ?", key];
        // 遍历结果集
        while ([set next]) {
            model._id = [set intForColumn:@"id"];
            model.key = [set stringForColumn:@"key"];
            model.value = [set dataForColumn:@"value"];
            model.type = [set stringForColumn:@"type"];
            model.update_time = [set intForColumn:@"update_time"];
            model.expire_time = [set intForColumn:@"expire_time"];
        }
        [db commit];
    }];
    
    return model;
}

+ (void)setItemWithKey:(NSString *)key
                 value:(NSData *)value
                  type:(NSString *)type
             updateTime:(NSInteger)updateTime
            expireTime:(NSInteger)expireTime {
    
    [self openDB];
    
    [_dbQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *set = [db executeQuery:@"select * from common_cache where key = ?", key];
        if (set.next) { // 根据上面的查询，只会出现一组数据
//            NSLog(@"键名已存在，覆盖");
            if ([db executeUpdate:@"update common_cache set value = ?, type = ?, update_time = ?, expire_time = ? where key = ?", value, type, @(updateTime), @(expireTime), key]) {
//                NSLog(@"修改成功");
            } else {
                NSLog(@"键名已存在，覆盖失败");
            }
            [set close];
        }

        else {
            if ([db executeUpdate:@"insert into common_cache (key, value, type, update_time, expire_time) values(?,?,?,?,?)", key, value, type, @(updateTime), @(expireTime)]) {
//                NSLog(@"添加成功");
            } else {
                NSLog(@"新记录添加失败");
            }
        }
        
        [set close];
    }];
    
}


+ (void)deleteItemWithKey:(NSString *)key {
    
    [self openDB];
    
    [_dbQueue inDatabase:^(FMDatabase *db) {
        
        // 遍历结果集
        if ([db executeUpdate:@"delete from common_cache where key = ?", key]) {
//            NSLog(@"删除成功");
        } else {
            NSLog(@"记录删除失败");
        }
    }];    
}


#pragma mark - log
/** 查找 时间戳大于某个时间戳的打印记录 */
+ (NSArray *)queryLogsAfterTime:(NSInteger)time {
    
    [self openDB];
    
    NSMutableArray *logs = [[NSMutableArray alloc] init];
    
    [_dbQueue inDatabase:^(FMDatabase *db) {
        
        [db beginTransaction];
        FMResultSet *set = [db executeQuery:@"SELECT * FROM itboye_log WHERE time > ?", @(time)];
        // 遍历结果集
        while ([set next]) {
            ByCoreLogModel *model = [[ByCoreLogModel alloc] init];
            model._id = [set intForColumn:@"id"];
            model.time = [set longForColumn:@"time"];
            model.func = [set stringForColumn:@"func"];
            model.line = [set longForColumn:@"line"];
            model.content = [set dataForColumn:@"content"];
            model.context = [set dataForColumn:@"context"];
            
            [logs addObject:model]; // 添加
        }
        [db commit];
    }];
    
    
    return logs;
}

/** 添加新记录 */
+ (void)setLogWithFunc:(NSString *)func
                  line:(NSInteger)line
                  time:(NSInteger)time
               content:(NSData *)content
               context:(NSData *)context {
    
    [self openDB];
    
    [_dbQueue inDatabase:^(FMDatabase *db) {
        
        if ([db executeUpdate:@"insert into itboye_log (time, func, line, content, context) values(?,?,?,?,?)", @(time), func, @(line), content, context]) {
            NSLog(@"添加成功");
        } else {
            NSLog(@"添加失败");
        }
    }];
}

#pragma mark - address
/** 获得所有的省份 */
+ (NSArray *)queryAllProvinces {
    
    [self openDB];

    NSMutableArray *temp = [[NSMutableArray alloc] initWithCapacity:0];
    
    [_dbQueue inDatabase:^(FMDatabase *db) {
        
        [db beginTransaction];
        FMResultSet *set = [db executeQuery:@"SELECT * FROM common_province"];
        // 遍历结果集
        while ([set next]) {
            ByCoreProvinceModel *model = [[ByCoreProvinceModel alloc] init];
            model.id = [set intForColumn:@"id"];
            model.provinceID = [set stringForColumn:@"provinceID"];
            model.province = [set stringForColumn:@"province"];
            model.countryid = [set intForColumn:@"countryid"];
            
            [temp addObject:model]; // 添加
        }
        [db commit];
    }];
    
    return [temp copy];
}

/** 更具省份id获得所有的城市 */
+ (NSArray *)queryAllCitysWithProvinceID:(NSString *)proviceID {
    
    [self openDB];
    
    NSMutableArray *temp = [[NSMutableArray alloc] initWithCapacity:0];
    
    [_dbQueue inDatabase:^(FMDatabase *db) {
        
        [db beginTransaction];
        FMResultSet *set = [db executeQuery:@"SELECT * FROM common_city where father = ? ", [NSString stringWithFormat:@"%@", proviceID]];
        // 遍历结果集
        while ([set next]) {
            ByCoreCityModel *model = [[ByCoreCityModel alloc] init];
            model.id = [set intForColumn:@"id"];
            model.cityID = [set stringForColumn:@"cityID"];
            model.city = [set stringForColumn:@"city"];
            model.father = [set stringForColumn:@"father"];
            
            [temp addObject:model]; // 添加
        }
        [db commit];
    }];
    
    return [temp copy];
}
/** 根据城市id获得所有的地区 */
+ (NSArray *)queryAllAreasWithCityID:(NSString *)cityID {
    
    [self openDB];
    
    NSMutableArray *temp = [[NSMutableArray alloc] initWithCapacity:0];
    
    [_dbQueue inDatabase:^(FMDatabase *db) {
        
        [db beginTransaction];
        FMResultSet *set = [db executeQuery:@"SELECT * FROM common_area where father = ? ", [NSString stringWithFormat:@"%@", cityID]];
        // 遍历结果集
        while ([set next]) {
            ByCoreAreaModel *model = [[ByCoreAreaModel alloc] init];
            model.id = [set intForColumn:@"id"];
            model.areaID = [set stringForColumn:@"areaID"];
            model.area = [set stringForColumn:@"area"];
            model.father = [set stringForColumn:@"father"];
            
            [temp addObject:model]; // 添加
        }
        [db commit];
    }];
    
    return [temp copy];
}

+ (NSString *)getProvinceID:(NSString *)provinceStr {
    NSString *provinceID = @"";
    
    for (ByCoreProvinceModel *model in [self queryAllProvinces]) {
        if ([model.province isEqualToString:provinceStr]) {
            provinceID = model.provinceID;
            break;
        }
    }
    
    return provinceID;
}
+ (NSString *)getCityID:(NSString *)cityStr provinceID:(NSString *)provinceID {
    NSString *cityID = @"";
    
    for (ByCoreCityModel *model in [self queryAllCitysWithProvinceID:provinceID]) {
        if ([model.city isEqualToString:cityStr]) {
            cityID = model.cityID;
            break;
        }
    }
    
    return cityID;

}

@end
